import datetime

from django.db.models import Q

from houses.utils import house_info
from iHome.utils.views import LoginRequiredMixin
from orders.models import Order
from users.qiniu import upload_avatar
from .models import Area, House, HouseImage
from django.http import JsonResponse
from django.views import View
from django.db import transaction
from django.conf import settings
from iHome.utils.param_checking import image_file
import json

class Releaselistings(View):
    """需要登录才能进入，发布房源"""

    def post(self, request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        # 标题
        title = json_dict.get('title')
        # 价格
        price = json_dict.get('price')
        # 城区id
        area_id = json_dict.get('area_id')
        # 房屋地址
        address = json_dict.get('address')
        # 房间数目
        room_count = json_dict.get('room_count')
        # 房屋面积
        acreage = json_dict.get('acreage')
        # 房屋单元，如：几室几厅
        unit = json_dict.get('unit')
        # 房屋容纳的人数
        capacity = json_dict.get('capacity')
        # 房屋床铺的配置
        beds = json_dict.get('beds')
        # 房屋押金
        deposit = json_dict.get('deposit')
        # 最少入住天数
        min_days = json_dict.get('min_days')
        # 最大入住天数，0表示不限制
        max_days = json_dict.get('max_days')
        # 用户选择的设施信息id列表，如：[7, 8]
        facility = json_dict.get('facility')

        # 校验参数
        if not all([title, price, area_id, address,
                    room_count, acreage, unit,
                    capacity, beds, deposit, min_days, max_days, facility]):
            return JsonResponse({'errno': 4004,
                                 'errmsg': '缺少必传参数'})

        # 1.查询城区数据
        try:
            Area.objects.get(id=area_id)
        except Exception as e:
            return JsonResponse({'errno': 4004,
                                 'errmsg': '城区数据不存在'})

        # 保存地址信息
        try:
            house = House.objects.create(
                user=request.user,
                area_id=area_id,
                title=title,
                price=price,
                address=address,
                room_count=room_count,
                acreage=acreage,
                unit=unit,
                capacity=capacity,
                beds=beds,
                deposit=deposit,
                min_days=min_days,
                max_days=max_days,

            )
            for facility_inifo in facility:
                house.facility.add(facility_inifo)
        except Exception as e:
            return JsonResponse({'errno': 4001,
                                 'errmsg': '房源保存失败'})
        data={'house_id': house.id}

        return JsonResponse({'errno': 0,
                             'errmsg': '发布成功',
                             'data': data})

    def get(self, request):
        '''房屋数据搜索-'''
        # 接受参数
        aid = request.GET.get('aid')
        start_day = request.GET.get('sd')
        end_day = request.GET.get('ed')
        sort_key = request.GET.get('sk', 'new')
        page = request.GET.get('p', '1')

        # 2.验证
        if not all([aid, start_day, end_day]):
            return JsonResponse({'errno': 4103, 'errmsg': '参数错误'})
        # 3.查询数据库
        # 时间校验与查询数据

        if start_day:
            startday = datetime.datetime.strptime(start_day, '%Y-%m-%d')
            if end_day:
                endday = datetime.datetime.strptime(end_day, '%Y-%m-%d')
                if startday > endday:
                    return JsonResponse({'erron': 4103, 'errmsg': '参数错误'})
                else:
                    try:
                        houses = House.objects.filter(area_id=aid)
                        # 开始时间<结束时间 结束时间>开始时间
                        orders = Order.objects.filter(begin_date__lt=endday, end_date__gt=start_day, house__in=houses,
                                                      status__in=[0, 1, 2, 3, 4])
                        # 查询订单中的房屋id
                        if not orders:
                            if sort_key:
                                if sort_key == 'booking':
                                    houses = House.objects.filter(area_id=aid).order_by('-order_count')
                                elif sort_key == 'price-inc':
                                    houses = House.objects.filter(area_id=aid).order_by('price')
                                elif sort_key == 'price-des':
                                    houses = House.objects.filter(area_id=aid).order_by('-price')
                                else:
                                    houses = House.objects.filter(area_id=aid).order_by('-create_time')

                                data = house_info(houses, page)

                                # 4.返回响应
                                return JsonResponse({"errno": 0, "errmsg": "请求成功", "data": data})

                        house_id_list = []
                        for order in orders:
                            house = order.house
                            if house.area_id == aid:
                                house_id_list.append(house.id)
                            house_id_list.append(order.house.id)

                        if sort_key:
                            if sort_key == 'booking':
                                houses = House.objects.filter(~Q(id__in=house_id_list) & Q(area_id=aid)).order_by(
                                    '-order_count')
                            elif sort_key == 'price-inc':
                                houses = House.objects.filter(~Q(id__in=house_id_list) & Q(area_id=aid)).order_by(
                                    'price')
                            elif sort_key == 'price-des':
                                houses = House.objects.filter(~Q(id__in=house_id_list) & Q(area_id=aid)).order_by(
                                    '-price')
                            else:
                                houses = House.objects.filter(~Q(id__in=house_id_list) & Q(area_id=aid)).order_by(
                                    '-create_time')

                            data = house_info(houses, page)

                            # 4.返回响应
                            return JsonResponse({"errno": 0, "errmsg": "ok", "data": data})

                    except Exception as e:
                        return JsonResponse({'errno': 4004, 'errmsg': '数据错误'})


class ShowHouseView(View):
    #首页展示房源 王荣桓

    def get(self, request):
        try:
            houses = House.objects.order_by('order_count')[:5]
        except Exception as e:
            return JsonResponse({'errno':4001,
                                 'errmsg':'获取信息失败'})
        data = []
        for house in houses:
            data.append({
                'house_id':house.id,
                'img_url':settings.QINIU_BUCKET_URL +'/'+ str(house.index_image_url),
                'title':house.title
            })
        return JsonResponse({'errno':0,
                             'errmsg':'ok',
                             'data':data})


class HouseDetailView(View):
    #房屋详情页 王荣桓

    def get(self, request, house_id):
        try:
            house = House.objects.get(id=house_id)
        except Exception as e:
            return JsonResponse({'errno': 4001, 'errmsg': '房屋不存在'})
        comments_list = []
        try:
            order_item = Order.objects.filter(house=house)
        except Exception as e:
            return JsonResponse({'errno': 4001, 'errmsg': '数据库操作失败'})

        for order in order_item:
            comments_list.append({
                'comment': order.comment,
                'ctime': order.create_time,
                'user_name': order.user.username
            })
        list = []
        try:
            house_imgages = HouseImage.objects.filter(house=house)
        except Exception as e:
            return JsonResponse({'errno': 4001, 'errmsg': '数据库操作失败'})
        for house_img in house_imgages:
            list.append(settings.QINIU_BUCKET_URL +'/'+ house_img.url)

        facility_list = []
        for facility in house.facility.all():
            facility_list.append(facility.id)

        house_dict = {
            'acreage': house.acreage,
            'address': house.address,
            'beds': house.beds,
            'capacity': house.capacity,
            'comments': comments_list,
            'deposit': house.deposit,
            'facilities': facility_list,
            'hid': house.id,
            'img_urls': list,
            'max_days': house.max_days,
            'min_days': house.min_days,
            'price': house.price,
            'room_count': house.room_count,
            'title': house.title,
            'unit': house.unit,
            'user_avatar': settings.QINIU_BUCKET_URL +'/'+ str(house.user.avatar),
            'user_id': int(house.user.id),
            'user_name': house.user.username,
        }
        if request.user.is_authenticated:
            house_info = {'house': house_dict,
                          'user_id': request.user.id}
        else:
            house_info = {'house': house_dict,
                          'user_id': -1}
        return JsonResponse({'errno': 0,
                             'errmsg': 'ok',
                             "data": house_info})

